package org.black.phoneUtility.sms.reply.app.activity;

import org.black.phoneUtility.R;
import org.black.phoneUtility.database.sqlite.PhoneUtilitySQLiteOpenHelper;
import org.black.phoneUtility.sms.reply.appwidget.SmsReplyAppWidgetProvider;
import org.black.phoneUtility.sms.reply.provider.SmsReplyContract;
import org.black.phoneUtility.sms.reply.widget.SmsReplyAppWidgetListCursorAdapter;

import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.appwidget.AppWidgetManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class SmsReplyAppWidgetConfigurationActivity extends Activity implements
		LoaderCallbacks<Cursor> {
	private static final String LOG_TAG = SmsReplyAppWidgetConfigurationActivity.class
			.getName();

	private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	private ListView smsReplyAppWidgetListView = null;
	private SmsReplyAppWidgetListCursorAdapter smsReplyAppWidgetListCursorAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setResult(RESULT_CANCELED);
		setContentView(R.layout.sms_reply_appwidget_configure);

		this.smsReplyAppWidgetListView = (ListView) findViewById(R.id.smsReplyAppwidgetConfigureListView);

		this.smsReplyAppWidgetListCursorAdapter = new SmsReplyAppWidgetListCursorAdapter(
				this, null, 0);
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		if (extras != null) {
			appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
		}
		if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}
		this.smsReplyAppWidgetListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						try {
							final Context context = SmsReplyAppWidgetConfigurationActivity.this;
							AppWidgetManager localAppWidgetManager = AppWidgetManager
									.getInstance(context);
							PhoneUtilitySQLiteOpenHelper phoneUtilitySQLiteOpenHelper = new PhoneUtilitySQLiteOpenHelper(
									getApplicationContext());
							SQLiteDatabase sqLiteDatabase = null;
							String title = null;
							boolean isActivated = false;
							Cursor cursor = null;
							try {
								sqLiteDatabase = phoneUtilitySQLiteOpenHelper
										.getWritableDatabase();
								sqLiteDatabase.beginTransaction();
								ContentValues createSmsReplyAppWidgetIdContentValues = new ContentValues();
								createSmsReplyAppWidgetIdContentValues
										.put(SmsReplyContract.SmsReplyAppWidgetIds.REFERENCE_SMS_REPLY_ID,
												id);
								createSmsReplyAppWidgetIdContentValues
										.put(SmsReplyContract.SmsReplyAppWidgetIds.APP_WIDGET_ID,
												appWidgetId);
								Long smsReplyAppWidgeId = sqLiteDatabase
										.insert(PhoneUtilitySQLiteOpenHelper.Tables.SMS.Reply.APP_WIDGET_IDS,
												null,
												createSmsReplyAppWidgetIdContentValues);
								sqLiteDatabase.setTransactionSuccessful();
								Log.d(LOG_TAG,
										"Create SmsReplyAppWidgetId. id: "
												+ smsReplyAppWidgeId);
								cursor = sqLiteDatabase
										.query(PhoneUtilitySQLiteOpenHelper.Tables.SMS.Reply.REPLIES,
												new String[] {
														SmsReplyContract.SmsReplies.TITLE,
														SmsReplyContract.SmsReplies.IS_ACTIVATED },
												SmsReplyContract.SmsReplies._ID
														+ " = ? ",
												new String[] { String
														.valueOf(id) }, null,
												null, null);

								if (cursor != null
										&& cursor.moveToFirst() == true) {
									title = cursor.getString(cursor
											.getColumnIndex(SmsReplyContract.SmsReplies.TITLE));
									isActivated = cursor.getInt(cursor
											.getColumnIndex(SmsReplyContract.SmsReplies.IS_ACTIVATED)) == 1 ? true
											: false;
								}
							} catch (Throwable throwable) {
								Log.e(LOG_TAG, "Database operation error!",
										throwable);
							} finally {
								sqLiteDatabase.endTransaction();
								if (cursor != null) {
									try {
										cursor.close();
									} catch (Throwable th) {
										Log.e(LOG_TAG, "Fail to close cursor",
												th);
									}
								}
								if (sqLiteDatabase != null) {
									if (sqLiteDatabase != null) {
										try {
											sqLiteDatabase.close();
										} catch (Throwable th) {
											Log.e(LOG_TAG,
													"Fail to close sqLiteDatabase",
													th);
										}
									}
								}
							}
							SmsReplyAppWidgetProvider.updateAppWidget(context,
									localAppWidgetManager, id, appWidgetId,
									isActivated, title);
							Intent resultValue = new Intent();
							resultValue.putExtra(
									AppWidgetManager.EXTRA_APPWIDGET_ID,
									appWidgetId);
							setResult(RESULT_OK, resultValue);
							finish();
						} catch (Throwable throwable) {
							Log.e(LOG_TAG, "Unknown Error!", throwable);
						}

					}
				});
		this.smsReplyAppWidgetListView
				.setAdapter(smsReplyAppWidgetListCursorAdapter);
		this.smsReplyAppWidgetListCursorAdapter.notifyDataSetChanged();
		getLoaderManager().initLoader(0, null, this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.smsReplyAppWidgetListView = null;
		this.smsReplyAppWidgetListCursorAdapter = null;
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		return new CursorLoader(this, SmsReplyContract.SmsReplies.CONTENT_URI,
				null, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		if (data != null && data.moveToFirst() == true) {
			if (smsReplyAppWidgetListCursorAdapter != null) {
				smsReplyAppWidgetListCursorAdapter.swapCursor(data);
				smsReplyAppWidgetListCursorAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		loader = null;
	}

}
